package com.droidnova.android.games.vortex;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.egl.EGLConfig;

import android.content.Context;
import android.graphics.PixelFormat;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.opengl.GLSurfaceView.Renderer;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.Toast;
	//public class VortexRenderer implements GLSurfaceView.Renderer {
		public class VortexRenderer	extends GLSurfaceView implements Renderer
		{
		//private float _red = 0.9f;
	   // private float _green = 0.2f;
	   // private float _blue = 0.2f;
		private float _red = 0.01f;
		private float _green = 0.01f;
		private float _blue = 0.02f;	
	   /** axis instance */
		private axis axis3d;
		/** points instance */
		private float z = -5.0f;			//Depth Into The Screen
		private points1 pointcube1;
		private lines linecube1;
		/** Angle For The axis */
		private float raxis; 	
		/** Angle For The points */
		private float rpoints; 
		int width , height;
		/* Rotation values */
		private float xrot;					//X Rotation
		float yrot;					//Y Rotation
		/* Rotation speed values */
		private float xspeed;				//X Rotation Speed
		private float yspeed;				//Y Rotation Speed
		/* Variables and factor for the input handler */
		private float oldX;
	    private float oldY;
		private final float TOUCH_SCALE = 0.2f;			//Proved to be good for normal rotation
		/** The Activity Context */
		private Context context;
		float _pcolors[] , _pvertices[];
		int _noVertices ;
		
		/** Is light enabled */
		private boolean light = false;
		/** Is blending enabled ( NEW ) */
		private boolean blend = false;

		/* The initial light values */
		private float[] lightAmbient = {0.5f, 0.5f, 0.5f, 1.0f};
		private float[] lightDiffuse = {1.0f, 1.0f, 1.0f, 1.0f};
		private float[] lightPosition = {0.0f, 0.0f, 2.0f, 1.0f};
			
		/* The buffers for our light values */
		private FloatBuffer lightAmbientBuffer;
		private FloatBuffer lightDiffuseBuffer;
		private FloatBuffer lightPositionBuffer;
		
		//camera rotation
		private final float piover180 = 0.0174532925f;
		private float lookupdown = 0.0f;
		private float crot;	
		private float heading;
		private float xpos;
		private float zpos;	 				//Y Rotation
		private float walkbias = 0;
		private float walkbiasangle = 0;
        
		private int camera_flag;
		/** Angle For The Rotation*/
		private float rtri;
		
		public VortexRenderer(Context context , points1 pointcube2 , lines linecube2,int camera_flag2) {	
		super(context);
		     
			//Set this as Renderer
			this.setRenderer(this);
			//Request focus, otherwise buttons won't react
			this.requestFocus();
			this.setFocusableInTouchMode(true);
			
			//
			this.context = context;	
			
			pointcube1 = pointcube2;
			
			linecube1 = linecube2;
			camera_flag = camera_flag2;
			
			ByteBuffer byteBuf = ByteBuffer.allocateDirect(lightAmbient.length * 4);
			byteBuf.order(ByteOrder.nativeOrder());
			lightAmbientBuffer = byteBuf.asFloatBuffer();
			lightAmbientBuffer.put(lightAmbient);
			lightAmbientBuffer.position(0);
			
			byteBuf = ByteBuffer.allocateDirect(lightDiffuse.length * 4);
			byteBuf.order(ByteOrder.nativeOrder());
			lightDiffuseBuffer = byteBuf.asFloatBuffer();
			lightDiffuseBuffer.put(lightDiffuse);
			lightDiffuseBuffer.position(0);
			
			byteBuf = ByteBuffer.allocateDirect(lightPosition.length * 4);
			byteBuf.order(ByteOrder.nativeOrder());
			lightPositionBuffer = byteBuf.asFloatBuffer();
			lightPositionBuffer.put(lightPosition);
			lightPositionBuffer.position(0);
			
			
			
			
			
		}
		

		@Override
		 public void onSurfaceCreated(GL10 gl, EGLConfig config) {
			
			//And there'll be light!
			gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, lightAmbientBuffer);		//Setup The Ambient Light
			gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightDiffuseBuffer);		//Setup The Diffuse Light
			gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightPositionBuffer);	//Position The Light
			gl.glEnable(GL10.GL_LIGHT0);											//Enable Light 0
			
			//Blending
			
			//gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
			
			//Full Brightness. 50% Alpha ( NEW )
			//gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE);		//Set The Blending Function For Translucency ( NEW )
		   //Really Nice Perspective Calculations
				gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST); 
		 }
		 
		    @Override
		    public void onSurfaceChanged(GL10 gl, int w, int h) {
		        width = w;
		        height = h;
		        Log.v("Width Height", "w h -> " + w + h);
		    	if(h == 0) { 						//Prevent A Divide By Zero By
					h = 1;                          //Making Height Equal One  
		    	}
		    	gl.glViewport(0, 0, w, h);         //Reset The Current Viewport
		    	//Calculate The Aspect Ratio Of The Window
		    	gl.glMatrixMode(GL10.GL_PROJECTION); 	//Select The Projection Matrix
		    	gl.glLoadIdentity(); 
		    	
				GLU.gluPerspective(gl, 45.0f, (float)width / (float)height, 0.1f, 100.0f);
				gl.glMatrixMode(GL10.GL_MODELVIEW); 	//Select The Modelview Matrix
				gl.glLoadIdentity(); 					//Reset The Modelview Matrix
		    }
	    
	
	    
		@Override
	    public void onDrawFrame(GL10 gl ) {
			 	
	    	//float aspect_ratio = (float) width / height;
	    	//GLU.gluPerspective(gl, 70, aspect_ratio, 1, 100);
	    	// first clear the screen of any previous drawing
	        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
	        gl.glClearColor(_red, _green, _blue, 1.0f);
	     
	        // clear the color buffer to show the ClearColor we called above...
	        gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
	        
	        /*
	        gl.glLoadIdentity();
	        gl.glColor4f(1.0f, 1.0f, 1.0f, 0.5f);
	        gl.glTranslatef(0.0f, 0.0f, z);	 //Move z units into the screen
	        gl.glRotatef(xrot, 1.0f, 0.0f, 0.0f);	//X
			gl.glRotatef(yrot, 0.0f, 1.0f, 0.0f);	//Y
			
			gl.glEnable(GL10.GL_BLEND);
			gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
			linecube1.draw(gl);
			*/
	        
	        gl.glLoadIdentity();  
	      //Check if the light flag has been set to enable/disable lighting
			if(light) {
				gl.glEnable(GL10.GL_LIGHTING);
			} else {
				gl.glDisable(GL10.GL_LIGHTING);
			}
			gl.glEnable(GL10.GL_BLEND);
			gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
			//Check if the blend flag has been set to enable/disable blending
			/*if(blend) {
				gl.glEnable(GL10.GL_BLEND);			//Turn Blending On ( NEW )
				gl.glDisable(GL10.GL_DEPTH_TEST);	//Turn Depth Testing Off ( NEW )
				
			} else {
				gl.glDisable(GL10.GL_BLEND);		//Turn Blending On ( NEW )
				gl.glEnable(GL10.GL_DEPTH_TEST);	//Turn Depth Testing Off ( NEW )
			}*/
	        gl.glTranslatef(0.0f, 0.0f, z);	 //Move z units into the screen
	        
	        //Rotate around the axis based on the rotation matrix (rotation, x, y, z)
		      if(camera_flag==0)
		      {
				gl.glRotatef(xrot, 1.0f, 0.0f, 0.0f);	//X
				gl.glRotatef(yrot, 0.0f, 1.0f, 0.0f);	//Y
		      }
		      else
		      {
		    	  gl.glRotatef(rtri, 0.0f, 1.0f, 0.0f);	//Rotate The Triangle On The Y axis ( NEW ) 
		      }
			
	        pointcube1.draw(gl);
	        gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	        linecube1.draw(gl);
	    	
	    	//Change rotation factors
			xrot += xspeed;
			yrot += yspeed;
			rtri += 2.0f; 
	    }
	    
	    
	  
		
		
		@Override
		public boolean onTouchEvent(MotionEvent event) {
			//
			float x = event.getX();
	        float y = event.getY();
	       // Log.v("x","x"+x);
	      //  Log.v("y","y"+y);
	        //If a touch is moved on the screen
	        if(event.getAction() == MotionEvent.ACTION_MOVE) {
	        	//Calculate the change
	        	float dx = x - oldX;
		        float dy = y - oldY;
		        Log.v("dx","dx"+dx);
		        Log.v("dy","dy"+dy);
		        
	        	//Define an upper area of 10% on the screen
	        	int upperArea = this.getHeight() / 10;
	        	Log.v("touch","touch");
	        	//Zoom in/out if the touch move has been made in the upper
	        	if(y < upperArea) {
	        		Log.v("upper","upper");
	        		z -= dx * TOUCH_SCALE / 2;
	        		Log.v("z","z"+z);
	        	//Rotate around the axis otherwise
	        	} else {  
	
	        		Log.v("rot","rot");
	    	        xrot += dy * TOUCH_SCALE;
	    	        yrot += dx * TOUCH_SCALE;
	        			
	        	}  
	        	//a press on the screen to activate blending
	        } else if(event.getAction() == MotionEvent.ACTION_UP) {
	        	//Define an upper area of 10% to define a lower area
	        	int upperArea = this.getHeight() / 4;
	        	int lowerArea = this.getHeight() - upperArea;
	        	
	        	//
	        	if(y > lowerArea) {
	        		//Change the blend setting if the lower area left has been pressed ( NEW ) 
	        		if(x < (this.getWidth() / 2)) {
	        			if(blend) {
	        				blend = false;
	            		} else {
	            			blend = true;
	            		}
	        			
	        		//Change the light setting if the lower area right has been pressed 
	        		} else {
	        			if(light) {
	            			light = false;
	            		} else {
	            			light = true;
	            		}	
	        		}
	        	}
	        }
	        
	        //Remember the values
	        oldX = x;
	        oldY = y;
	        
	        //We handled the event
			return true;
		}
		
		public void setPointcube(points1 pointcube3) {
		       pointcube1 = pointcube3;
		    }
		
		public void setlinecube(lines linecube3) {
		       linecube1 = linecube3;
		    } 
		
		public void setCameraflag(int flag)
		 {
			 camera_flag=flag;
		 } 
	
	}
	
	
	

